package com.kitty.game.activity.service.time;

import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.Position;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.cache.DataCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 战神处理类
 */
@Component
public class ZhanShenHandler extends FightActivityHandler {
    /**
     * 天墉城、无名小镇和东海渔村
     */
    private static final List<Integer> MAPIDS = Arrays.asList(6000);
    /**
     * 每小时刷新战神的数量
     */
    private static final int COUNT_PER_HOUR = 5;
    @Autowired
    FightService fightService;
    @Autowired
    RedisService redisService;
    /**
     * 战神npc显示名称
     */
    private static final String NAME = "战神";
    private static final String SMALL_BOSS_NAME = "战将";
    /**
     * 战神icon
     */
    private static final int ICON = 6232;
    /**
     * 战神持续时间，单位毫秒
     */
    private static final long NPC_CONTINUED_TIME = 60 * TimeUtil.ONE_MINUTE;
    private static final String CONTENT = "只有最勇敢的人，才可以得到最好的装备！\n#R战斗结束时死亡的角色会受到惩罚。#n[我要挑战/" + NpcButton.FIGHT_TO_ZHANSHEN.getKey() + "][离开]";
    private static final String PIRATE_COME_NUMOR = "听说在#Z桃柳林#Z有天界的战神下凡，大家快去寻找吧！";
    private static final String IN_FIGHT = "即使是神仙，也不能一次对付两个。[离开]";
    /**
     * 最少组队人数
     */
    private static final int MIN_TEAM_COUNT = 1;
    private static final String TEAM_COUNT_NOT_ENOUGH = "你还是凑齐三个人再来向我挑战吧！[离开]";
    private static final int ACCEPT_MIN_LEVEL = 40;
    private static final String TEAM_LEVEL_NOT_ENOUGH = "#Y{0}#n的等级还没有{1}级。[离开]";

    /**
     * 刷新战神，显示在对应的地图上
     */
    public void flushNpc() {
     //   LoggerFunction.BUG.getLogger().warn("开始刷新战神！！！");

        int num = Integer.parseInt( DataCache.REDIS_DATA.get("zhanshen_refresh_number"));
        for (int i = 0; i < num; i++) {
            /**随机地图*/
            int mapId = getRandomMapId();
            createNpc(mapId);
        }
        SpringUtils.getBean(ChatService.class).sendNumor(PIRATE_COME_NUMOR, Const.BRODCAST_MSG_TYPE_ROLE);
    }

    private int getRandomMapId() {
        int rand = ThreadLocalRandom.current().nextInt(MAPIDS.size());
        return MAPIDS.get(rand);
    }

    private void createNpc(int mapId) {
        Position position = getRandomPosition(mapId);

        NPC npc = new NPC();
        npc.setIcon(ICON);
        npc.setId(SpringUtils.getBean(NewBossService.class).getTempNpcId());
        npc.setX(position.getX());
        npc.setY(position.getY());
        npc.setFangxiang((short) new Random().nextInt(8));/*随机方向*/
        npc.setMapId(mapId);
        npc.setCreateTime(System.currentTimeMillis());
        npc.setEndTime(npc.getCreateTime() + NPC_CONTINUED_TIME);
        npc.setType(NPC.TYPE_ZHAN_SHEN);
        npc.setContent(CONTENT);
        npc.setName(NAME);
        npc.setBossSetName(NAME);
        bossService.addTaskNpc(npc);
        bossService.broadcastNpcShow(null, npc);
    }

    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }

        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return TEAM_COUNT_NOT_ENOUGH;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());
        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
        if (names != null) {
            return MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
        }

        names = teamService.checkMember(team, memberRole -> getRoleRemainCount(memberRole) <= 0);
        if (names != null) {
            return "#R" + names + "#n没有挑战次数";
        }
        if (getRoleRemainCount(role) <= 0) {
            return "#R" + role.getName() + "#n没有挑战次数";
        }
        return null;
    }

    private byte getRoleRemainCount(Role role) {
        return (byte) SpringUtils.getActivityService().getRemainCount(role, ActivityType.zhansheng_ACTIVTY);
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = newBossParamList(role, bossNpc);
        BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
        bossFightParam.setNpcId(bossNpc.getId());
        int maxRoleLevel = teamService.getMaxRoleLevelInTeam(role);
        bossFightParam.setNpcLevel((short) maxRoleLevel);
        Fight fight = bossService.startFightToBoss(role, bossFightParam);
    }

    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;

        /**npc对应的加在第1个*/
        BossSet bossSet = bossService.getBossSet(bossNpc.getBossSetName());
        bossParamList.add(new BossParam(bossSet, bossNpc.getName()));

        /**加count-1个*/
        for (int i = 1; i < count; i++) {
            bossSet = bossService.getBossSet(SMALL_BOSS_NAME);
            bossParamList.add(new BossParam(bossSet, SMALL_BOSS_NAME));
        }

        return bossParamList;
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_zhanShen;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {
        clearNpc(bossNpc);
    }

    private void clearNpc(NPC npc) {
        if (npc == null) {
            return;
        }

        bossService.delTaskNpc(npc);
        removeUsedPosition(npc.getMapId(), npc.getX(), npc.getY());
        bossService.broadcastNpcHide(null, npc);
    }

    /**
     * 这里可以写单独的处理
     * @param role
     * @param fightEndEvent
     * @param bossNpc
     */
    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        fightService.sendBossBasicsReward(role,fightEndEvent);
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.zhansheng_ACTIVTY, 1);
        fightService.sendBossExtReward(role,fightEndEvent);
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {
        clearNpc(npc);
    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);

        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
}
